import {
    Image,
    StyleSheet,
    View,
    Text,
    TouchableOpacity,
    useWindowDimensions,
    Animated,
    FlatList,
    RefreshControl, ActivityIndicator, ImageBackground, Modal
} from 'react-native';
import {Stack, useRouter} from "expo-router";
import { scaleSize } from "@/utils/screenSize"
import AntDesign from '@expo/vector-icons/AntDesign';
import {SceneMap, TabView} from "react-native-tab-view";
import * as React from "react";
import {useEffect, useState} from "react";
import empty_icon from "@/assets/images/concern/empty_fan.png";
import activityTag from "@/assets/images/collection/activityTag.png";
import dateTimeIcon from "@/assets/images/collection/dateTime.png";
import addressIcon from "@/assets/images/collection/address.png";
import headerTagImg from "@/assets/images/activityImg/headerTag_img.png"
import { getMyActivityList } from "@/services/activityServices";
import { loadingService } from "@/utils/loadingServer";
import {format} from "date-fns";
import {parseFloat} from "@/utils";
import Empty from "@/components/empty";

enum activityType {
    cancel,
    waiting,
    starting,
    ending,
    exam
};

const JoinRoute = ({ currentIndex }) => {
    const [data, setData] = useState([]);
    const [loading, setLoading] = useState(false);
    const [refreshing, setRefreshing] = useState(false);
    const [triggerRefresh, setTriggerRefresh] = useState(false);
    const [page, setPage] = useState(1);
    const [current, setCurrent] = useState(1);
    const [size, setSize] = useState(10);
    const [pages, setPages] = useState(0);
    const [noMore, setNoMore] = useState(false);
    const [refreshingText, setRefreshingText] = useState('下拉刷新');
    const scrollY = new Animated.Value(0); // 用于跟踪滚动偏移

    const [foundTextModel, setFoundTextModel] = useState(false);

    const router = useRouter();

    // 自定义加载图标组件
    const RefreshControlHeader = ({ refreshing, text }) => (
        refreshing && (
            <View style={styles.refreshHeader}>
                <Text style={styles.refreshText}>{text}</Text>
            </View>
        )
    );

    const getActivityList = function (requestData?) {
        const params = {
            myType: 1,
            current: 1,
            size: 10,
            ...requestData,
        };
        getMyActivityList(params)
            .then(res => {
                if (params?.current == 1) {
                    setData([...res?.data?.items]);
                } else {
                    setData([...data, ...res?.data?.items]);
                };
                setPages(res?.data?.pages);
                setCurrent(res?.data?.current);
                setRefreshing(false);
                setRefreshingText('下拉刷新');
            })
            .catch(err => {
                console.log('err', err)
                setRefreshing(false);
            })
    };

    // 初次加载数据
    useEffect(() => {
        getActivityList();
    }, []);

    const goActivityDetail = function (id) {
        router.push(`/activityDetail/${id}`)
    };

    useEffect(() => {
        if (triggerRefresh) {
            handleRefresh();
            setTriggerRefresh(false); // Reset trigger
        }
    }, [triggerRefresh]);

    const loadMoreData = () => {
        // if (loading) return;
        if (data.length > 10) {
            setLoading(true);
        };

        if (current === pages) {
            setLoading(false)
            setNoMore(true)
            return;
        };
        // 模拟网络请求来获取更多数据
        const params = {
            current: current + 1,
        }
        getActivityList(params)
    };

    const handleRefresh = () => {
        setRefreshing(true);
        setRefreshingText('正在刷新...');
        setPage(1);

        // 模拟网络请求来获取新数据
        getActivityList({ current: 1 });
    };

    const renderFooter = () => {
        if (!loading) return null;
        if (data.length <= 0) return null;
        return (
            <>
                {
                    loading && (
                        <View style={{ paddingVertical: 10, flexDirection: "row", justifyContent: "center", alignItems: "center" }}>
                            <ActivityIndicator size="small" />
                            <Text style={{ textAlign: 'center', fontSize: 14, color: "#676978", marginLeft: 5, }}>疯狂加载中</Text>
                        </View>
                    )
                }
            </>
        );
    };

    const handleScroll = Animated.event(
        [{ nativeEvent: { contentOffset: { y: scrollY } } }],
        {
            useNativeDriver: false,
            listener: event => {
                const offsetY = event.nativeEvent.contentOffset.y;

                if (!refreshing) {
                    // 根据下拉距离更新文本
                    if (offsetY < -100) {
                        setRefreshingText('松开刷新'); // 超过 -100 的偏移量显示松开刷新
                    } else if (offsetY < 0) {
                        setRefreshingText('下拉刷新'); // 在 -100 到 0 之间时显示下拉刷新
                    }
                }
            },
        }
    );

    const onScrollEnd = () => {
        scrollY.addListener(({ value }) => {
            if (!refreshing && value < -100) {
                setTriggerRefresh(true); // 触发刷新
            }
        });
    };

    const computedTime = function (startT, endT) {
        // console.log('startT', startT);
        // if (!isValid(startT) || !isValid(endT)) return  "";
        const day1 = format(startT, "yyMMdd");
        const day2 = format(endT, "yyMMdd");
        if (day1 == day2) {
            return `${format(startT, "MM.dd")} ${format(startT, "mm:ss")}-${format(endT, "mm:ss")}`
        };
        return `${format(startT, "MM.dd")} ${format(startT, "mm:ss")}-${format(startT, "MM.dd")} ${format(endT, "mm:ss")}`
    };


    const ActivityItem = ({ item }) => {
        const { type } = item;
        return (
            <TouchableOpacity onPress={() => goActivityDetail(item?.activityId)}>
                <View style={styles.activityContainer}>
                    <View style={styles.activitybody}>
                        <View style={styles.activityBanner}>
                            <Image source={{ uri: item.coverUrl }} style={{ width: "100%", height: "100%" }} />
                            {
                                item.activityStatus == 1 && (
                                    <ImageBackground source={headerTagImg} style={styles.activityTagWarp}>
                                        <View style={[{ transform: [{rotateZ:'-45deg'}]}, styles.tag]}>
                                            <Text style={styles.tagText}>待开始</Text>
                                        </View>
                                    </ImageBackground>
                                )
                            }

                            {
                                (item.activityStatus == 2)  && (
                                    <ImageBackground source={headerTagImg} style={styles.activityTagWarp}>
                                        <View style={[{ transform: [{rotateZ:'-45deg'}]}, styles.tag]}>
                                            <Text style={styles.tagText}>进行中</Text>
                                        </View>
                                    </ImageBackground>
                                )
                            }



                            {
                                item.activityStatus == 3 && (
                                    <View style={styles.activityType}>
                                        <Text style={styles.activityTypeText}>已结束</Text>
                                    </View>
                                )
                            }

                            {
                                item.activityStatus === 4 && (
                                    <View style={styles.activityType}>
                                        <Text style={styles.activityTypeText}>已取消</Text>
                                    </View>
                                )
                            }

                        </View>
                        <View style={styles.activityContent}>
                            <View style={styles.activityTitleWarp}>
                                <Text
                                    style={styles.activityTitle}
                                    numberOfLines={2}
                                    ellipsizeMode="tail"
                                >{ item.title }</Text>
                            </View>
                            <View style={styles.activityTag}>
                                <Text style={styles.activityTagText}>{ item.typeName }</Text>
                            </View>
                            <View style={styles.activityDateWarp}>
                                <View style={styles.addressIcon}>
                                    <Image source={dateTimeIcon } style={{ width: '100%', height: "100%" }} />
                                </View>
                                <Text style={ styles.activityDate }>{ computedTime(item?.durationStartTime, item?.durationEndTime) }</Text>
                            </View>
                            <View style={styles.activityAdressWarp}>
                                <View style={styles.addressIcon}>
                                    <Image source={addressIcon} style={{ width: '100%', height: "100%" }} />
                                </View>
                                <Text style={styles.activityAdress}>{ item.destName }</Text>
                            </View>
                        </View>

                    </View>

                    {
                        item.activityStatus == 2 && (
                            <View style={styles.activityFooter}>
                                <View style={styles.joinList}>
                                    <View style={styles.joinListWarp}>
                                        {
                                            item.members.map((it:any, index: number) => {
                                                if (index == 0) {
                                                    return (
                                                        <View style={styles.joinAvator}>
                                                            <Image source={{ uri: it.avator }} style={{ width: "100%", height: "100%" }} />
                                                        </View>
                                                    )
                                                } else if (index <= 3 ) {
                                                    return (
                                                        <View style={[styles.joinAvator,styles.maLeft]}>
                                                            <Image source={{ uri:it.avator }} style={{ width: "100%", height: "100%" }} />
                                                        </View>
                                                    )
                                                }
                                            })
                                        }
                                        {
                                            item.activityStatus == 1 && (
                                                <View style={styles.joinContent}>
                                                    <Text style={styles.joinContentText}>正在招募...</Text>
                                                </View>
                                            )
                                        }

                                    </View>

                                </View>
                                <View style={styles.activityMoney}>
                                    <Text style={styles.activityMoneyText}>¥{ parseFloat(item?.ticketsPrice) }</Text>
                                </View>
                            </View>
                        )
                    }
                    {/*{*/}
                    {/*    activityType.waiting == type && (*/}
                    {/*        <View style={styles.activityFooter}>*/}
                    {/*           <TouchableOpacity onPress={() => setFoundTextModel(true)}>*/}
                    {/*               <View style={styles.activityMoney}>*/}
                    {/*                   <Text style={styles.activityMoneyText}>退出</Text>*/}
                    {/*               </View>*/}
                    {/*           </TouchableOpacity>*/}
                    {/*        </View>*/}
                    {/*    )*/}
                    {/*}*/}

                    {
                        (item.isComment === 0 && item.activityStatus == 3) && (
                            <View style={styles.activityFooterComment}>
                                <TouchableOpacity onPress={() => setFoundTextModel(true)}>
                                    <View style={styles.activityMoneyComment}>
                                        <Text style={styles.activityMoneyTextComment}>去评论</Text>
                                    </View>
                                </TouchableOpacity>
                            </View>
                        )
                    }
                </View>
            </TouchableOpacity>
        )
    };

    return (
       <>
           <FlatList
               data={data}
               renderItem={({ item }) => <ActivityItem item={item} />}
               keyExtractor={(item, index) => index.toString()}
               onEndReached={loadMoreData}
               onEndReachedThreshold={0.5} // 当滚动到距离底部还有50%的时候触发
               ListFooterComponent={renderFooter}
               refreshControl={
                   <RefreshControl
                       refreshing={refreshing}
                       // onRefresh={handleRefresh} // 绑定刷新函数
                       title={refreshing ? '' : refreshingText} // 在正在刷新状态时不显示文本
                       titleColor="#333" // 设置提示文字颜色
                       tintColor="transparent" // 隐藏刷新指示器
                   />
               }
               onScroll={handleScroll}
               onScrollEndDrag={onScrollEnd}
               ListHeaderComponent={<RefreshControlHeader refreshing={refreshing} text={refreshingText} />}
               ListEmptyComponent={<Empty title={"你还没有参加活动"} />}
           />

           <Modal
               animationType="fade"
               transparent={true}
               visible={foundTextModel}
           >
               <TouchableOpacity
                   activeOpacity={1}
                   onPress={(event) => {
                       if (event.target === event.currentTarget) {
                           setFoundTextModel(false);
                       }
                   }}
                   style={styles.becameModelContainer}
               >
                   <View style={styles.becameModelWrap}>
                       <View style={styles.becameModelTitle}>
                           <Text style={styles.becameModelTitleText}>退出</Text>
                       </View>
                        <View>
                            <Text style={{textAlign: "center", marginBottom: 34, color: "#676978"}}>确定退出活动</Text>
                        </View>
                       <View style={styles.becameFootWrap}>
                           <TouchableOpacity onPress={() => setFoundTextModel(false)}>
                               <View style={styles.cancelBtn}>
                                   <Text style={styles.cancelBtnText} >取消</Text>
                               </View>
                           </TouchableOpacity>
                           <TouchableOpacity onPress={() => setFoundTextModel(false)}>
                               <View style={styles.okBtn}>
                                   <Text style={styles.okBtnText}>确认</Text>
                               </View>
                           </TouchableOpacity>
                       </View>
                   </View>
               </TouchableOpacity>

           </Modal>
       </>
    );
};


const CreateRoute = ({ currentIndex }) => {
    const [data, setData] = useState([]);
    const [loading, setLoading] = useState(false);
    const [refreshing, setRefreshing] = useState(false);
    const [triggerRefresh, setTriggerRefresh] = useState(false);
    const [page, setPage] = useState(1);
    const [current, setCurrent] = useState(1);
    const [size, setSize] = useState(10);
    const [pages, setPages] = useState(0);
    const [noMore, setNoMore] = useState(false);
    const [refreshingText, setRefreshingText] = useState('下拉刷新');
    const scrollY = new Animated.Value(0); // 用于跟踪滚动偏移

    const [foundTextModel, setFoundTextModel] = useState(false);

    const router = useRouter();

    // 自定义加载图标组件
    const RefreshControlHeader = ({ refreshing, text }) => (
        refreshing && (
            <View style={styles.refreshHeader}>
                <Text style={styles.refreshText}>{text}</Text>
            </View>
        )
    );

    const getActivityList = function (requestData?) {
        const params = {
            myType: 2,
            current: 1,
            size: 10,
            ...requestData,
        };
        console.log('getActivityList', params);
        getMyActivityList(params)
            .then(res => {
                if (params?.current == 1) {
                    setData([...res?.data?.items]);
                } else {
                    setData([...data, ...res?.data?.items]);
                };
                setPages(res?.data?.pages);
                setCurrent(res?.data?.current);
                setRefreshing(false);
                setRefreshingText('下拉刷新');
            })
            .catch(err => {
                console.log('err', err)
                setRefreshing(false);
            })
    };

    // 初次加载数据
    useEffect(() => {
        getActivityList();
    }, []);

    useEffect(() => {
        if (triggerRefresh) {
            handleRefresh();
            setTriggerRefresh(false); // Reset trigger
        }
    }, [triggerRefresh]);

    const loadMoreData = () => {
        // if (loading) return;

        setLoading(true);
        if (current === pages) {
            setLoading(false)
            setNoMore(true)
            return;
        };
        // 模拟网络请求来获取更多数据
        const params = {
            current: current + 1,
        }
        getActivityList(params)
    };

    const handleRefresh = () => {
        setRefreshing(true);
        setRefreshingText('正在刷新...');
        setPage(1);

        // 模拟网络请求来获取新数据
        getActivityList({ current: 1 });
    };

    const renderFooter = () => {
        if (!loading) return null;
        if (data.length <= 0) return null;
        return (
            <>
                {
                    loading && (
                        <View style={{ paddingVertical: 10, flexDirection: "row", justifyContent: "center", alignItems: "center" }}>
                            <ActivityIndicator size="small" />
                            <Text style={{ textAlign: 'center', fontSize: 14, color: "#676978", marginLeft: 5, }}>疯狂加载中</Text>
                        </View>
                    )
                }
            </>
        );
    };

    const handleScroll = Animated.event(
        [{ nativeEvent: { contentOffset: { y: scrollY } } }],
        {
            useNativeDriver: false,
            listener: event => {
                const offsetY = event.nativeEvent.contentOffset.y;

                if (!refreshing) {
                    // 根据下拉距离更新文本
                    if (offsetY < -100) {
                        setRefreshingText('松开刷新'); // 超过 -100 的偏移量显示松开刷新
                    } else if (offsetY < 0) {
                        setRefreshingText('下拉刷新'); // 在 -100 到 0 之间时显示下拉刷新
                    }
                }
            },
        }
    );

    const onScrollEnd = () => {
        scrollY.addListener(({ value }) => {
            if (!refreshing && value < -100) {
                setTriggerRefresh(true); // 触发刷新
            }
        });
    };

    const computedTime = function (startT, endT) {
        // console.log('startT', startT);
        // if (!isValid(startT) || !isValid(endT)) return  "";
        const day1 = format(startT, "yyMMdd");
        const day2 = format(endT, "yyMMdd");
        if (day1 == day2) {
            return `${format(startT, "MM.dd")} ${format(startT, "mm:ss")}-${format(endT, "mm:ss")}`
        };
        return `${format(startT, "MM.dd")} ${format(startT, "mm:ss")}-${format(startT, "MM.dd")} ${format(endT, "mm:ss")}`
    };

    const goActivityDetail = function (id) {
        router.push(`/activityDetail/${id}`)
    };


    const ActivityItem = ({ item }) => {
        const { type } = item;
        return (
            <TouchableOpacity onPress={() => goActivityDetail(item.activityId)}>
                <View style={styles.activityContainer}>
                    <View style={styles.activitybody}>
                        <View style={styles.activityBanner}>
                            <Image source={{ uri: item.coverUrl }} style={{ width: "100%", height: "100%" }} />
                            {
                                item.activityStatus == 1 && (
                                    <ImageBackground source={headerTagImg} style={styles.activityTagWarp}>
                                        <View style={[{ transform: [{rotateZ:'-45deg'}]}, styles.tag]}>
                                            <Text style={styles.tagText}>待开始</Text>
                                        </View>
                                    </ImageBackground>
                                )
                            }

                            {
                                (item.activityStatus == 2)  && (
                                    <ImageBackground source={headerTagImg} style={styles.activityTagWarp}>
                                        <View style={[{ transform: [{rotateZ:'-45deg'}]}, styles.tag]}>
                                            <Text style={styles.tagText}>进行中</Text>
                                        </View>
                                    </ImageBackground>
                                )
                            }



                            {
                                item.activityStatus == 3 && (
                                    <View style={styles.activityType}>
                                        <Text style={styles.activityTypeText}>已结束</Text>
                                    </View>
                                )
                            }

                            {
                                item.activityStatus === 4 && (
                                    <View style={styles.activityType}>
                                        <Text style={styles.activityTypeText}>已取消</Text>
                                    </View>
                                )
                            }

                        </View>
                        <View style={styles.activityContent}>
                            <View style={styles.activityTitleWarp}>
                                <Text
                                    style={styles.activityTitle}
                                    numberOfLines={2}
                                    ellipsizeMode="tail"
                                >{ item.title }</Text>
                            </View>
                            <View style={styles.activityTag}>
                                <Text style={styles.activityTagText}>{ item.typeName }</Text>
                            </View>
                            <View style={styles.activityDateWarp}>
                                <View style={styles.addressIcon}>
                                    <Image source={dateTimeIcon } style={{ width: '100%', height: "100%" }} />
                                </View>
                                <Text style={ styles.activityDate }>{ computedTime(item?.durationStartTime, item?.durationEndTime) }</Text>
                            </View>
                            <View style={styles.activityAdressWarp}>
                                <View style={styles.addressIcon}>
                                    <Image source={addressIcon} style={{ width: '100%', height: "100%" }} />
                                </View>
                                <Text style={styles.activityAdress}>{ item.destName }</Text>
                            </View>
                        </View>

                    </View>

                    {
                        item.activityStatus == 2 && (
                            <View style={styles.activityFooter}>
                                <View style={styles.joinList}>
                                    <View style={styles.joinListWarp}>
                                        {
                                            item.members.map((it:any, index: number) => {
                                                if (index == 0) {
                                                    return (
                                                        <View style={styles.joinAvator}>
                                                            <Image source={{ uri: it.avator }} style={{ width: "100%", height: "100%" }} />
                                                        </View>
                                                    )
                                                } else if (index <= 3 ) {
                                                    return (
                                                        <View style={[styles.joinAvator,styles.maLeft]}>
                                                            <Image source={{ uri:it.avator }} style={{ width: "100%", height: "100%" }} />
                                                        </View>
                                                    )
                                                }
                                            })
                                        }
                                        {
                                            item.activityStatus == 1 && (
                                                <View style={styles.joinContent}>
                                                    <Text style={styles.joinContentText}>正在招募...</Text>
                                                </View>
                                            )
                                        }

                                    </View>

                                </View>
                                <View style={styles.activityMoney}>
                                    <Text style={styles.activityMoneyText}>¥{ parseFloat(item?.ticketsPrice) }</Text>
                                </View>
                            </View>
                        )
                    }
                    {/*{*/}
                    {/*    activityType.waiting == type && (*/}
                    {/*        <View style={styles.activityFooter}>*/}
                    {/*           <TouchableOpacity onPress={() => setFoundTextModel(true)}>*/}
                    {/*               <View style={styles.activityMoney}>*/}
                    {/*                   <Text style={styles.activityMoneyText}>退出</Text>*/}
                    {/*               </View>*/}
                    {/*           </TouchableOpacity>*/}
                    {/*        </View>*/}
                    {/*    )*/}
                    {/*}*/}

                    {
                        (item.isComment === 0 && item.activityStatus == 3) && (
                            <View style={styles.activityFooterComment}>
                                <TouchableOpacity onPress={() => setFoundTextModel(true)}>
                                    <View style={styles.activityMoneyComment}>
                                        <Text style={styles.activityMoneyTextComment}>去评论</Text>
                                    </View>
                                </TouchableOpacity>
                            </View>
                        )
                    }

                </View>
            </TouchableOpacity>
        )
    };

    return (
        <>
            <FlatList
                data={data}
                renderItem={({ item }) => <ActivityItem item={item} />}
                keyExtractor={(item, index) => index.toString()}
                onEndReached={loadMoreData}
                onEndReachedThreshold={0.5} // 当滚动到距离底部还有50%的时候触发
                ListFooterComponent={renderFooter}
                refreshControl={
                    <RefreshControl
                        refreshing={refreshing}
                        // onRefresh={handleRefresh} // 绑定刷新函数
                        title={refreshing ? '' : refreshingText} // 在正在刷新状态时不显示文本
                        titleColor="#333" // 设置提示文字颜色
                        tintColor="transparent" // 隐藏刷新指示器
                    />
                }
                onScroll={handleScroll}
                onScrollEndDrag={onScrollEnd}
                ListHeaderComponent={<RefreshControlHeader refreshing={refreshing} text={refreshingText} />}
                ListEmptyComponent={<Empty title={"你还没有创建活动"} />}
            />

            <Modal
                animationType="fade"
                transparent={true}
                visible={foundTextModel}
            >
                <TouchableOpacity
                    activeOpacity={1}
                    onPress={(event) => {
                        if (event.target === event.currentTarget) {
                            setFoundTextModel(false);
                        }
                    }}
                    style={styles.becameModelContainer}
                >
                    <View style={styles.becameModelWrap}>
                        <View style={styles.becameModelTitle}>
                            <Text style={styles.becameModelTitleText}>退出</Text>
                        </View>
                        <View>
                            <Text style={{textAlign: "center", marginBottom: 34, color: "#676978"}}>确定退出活动</Text>
                        </View>
                        <View style={styles.becameFootWrap}>
                            <TouchableOpacity onPress={() => setFoundTextModel(false)}>
                                <View style={styles.cancelBtn}>
                                    <Text style={styles.cancelBtnText} >取消</Text>
                                </View>
                            </TouchableOpacity>
                            <TouchableOpacity onPress={() => setFoundTextModel(false)}>
                                <View style={styles.okBtn}>
                                    <Text style={styles.okBtnText}>确认</Text>
                                </View>
                            </TouchableOpacity>
                        </View>
                    </View>
                </TouchableOpacity>

            </Modal>
        </>
    );
};

const CheckRoute = ({ currentIndex }) => {
    const [data, setData] = useState([]);
    const [loading, setLoading] = useState(false);
    const [refreshing, setRefreshing] = useState(false);
    const [triggerRefresh, setTriggerRefresh] = useState(false);
    const [page, setPage] = useState(1);
    const [current, setCurrent] = useState(1);
    const [size, setSize] = useState(10);
    const [pages, setPages] = useState(0);
    const [noMore, setNoMore] = useState(false);
    const [refreshingText, setRefreshingText] = useState('下拉刷新');
    const scrollY = new Animated.Value(0); // 用于跟踪滚动偏移

    const [foundTextModel, setFoundTextModel] = useState(false);

    const router = useRouter();

    // 自定义加载图标组件
    const RefreshControlHeader = ({ refreshing, text }) => (
        refreshing && (
            <View style={styles.refreshHeader}>
                <Text style={styles.refreshText}>{text}</Text>
            </View>
        )
    );

    const getActivityList = function (requestData?) {
        const params = {
            myType: 3,
            current: 1,
            size: 10,
            ...requestData,
        };
        console.log('getActivityList', params);
        getMyActivityList(params)
            .then(res => {
                if (params?.current == 1) {
                    setData([...res?.data?.items]);
                } else {
                    setData([...data, ...res?.data?.items]);
                };
                setPages(res?.data?.pages);
                setCurrent(res?.data?.current);
                setRefreshing(false);
                setRefreshingText('下拉刷新');
            })
            .catch(err => {
                console.log('err', err)
                setRefreshing(false);
            })
    };

    // 初次加载数据
    useEffect(() => {
        getActivityList();
    }, []);

    useEffect(() => {
        if (triggerRefresh) {
            handleRefresh();
            setTriggerRefresh(false); // Reset trigger
        }
    }, [triggerRefresh]);

    const loadMoreData = () => {
        // if (loading) return;

        setLoading(true);
        if (current === pages) {
            setLoading(false)
            setNoMore(true)
            return;
        };
        // 模拟网络请求来获取更多数据
        const params = {
            current: current + 1,
        }
        getActivityList(params)
    };

    const handleRefresh = () => {
        setRefreshing(true);
        setRefreshingText('正在刷新...');
        setPage(1);

        // 模拟网络请求来获取新数据
        getActivityList({ current: 1 });
    };



    const renderFooter = () => {
        if (!loading) return null;
        if (data.length <= 0) return null;
        return (
            <>
                {
                    loading && (
                        <View style={{ paddingVertical: 10, flexDirection: "row", justifyContent: "center", alignItems: "center" }}>
                            <ActivityIndicator size="small" />
                            <Text style={{ textAlign: 'center', fontSize: 14, color: "#676978", marginLeft: 5, }}>疯狂加载中</Text>
                        </View>
                    )
                }
            </>
        );
    };

    const handleScroll = Animated.event(
        [{ nativeEvent: { contentOffset: { y: scrollY } } }],
        {
            useNativeDriver: false,
            listener: event => {
                const offsetY = event.nativeEvent.contentOffset.y;

                if (!refreshing) {
                    // 根据下拉距离更新文本
                    if (offsetY < -100) {
                        setRefreshingText('松开刷新'); // 超过 -100 的偏移量显示松开刷新
                    } else if (offsetY < 0) {
                        setRefreshingText('下拉刷新'); // 在 -100 到 0 之间时显示下拉刷新
                    }
                }
            },
        }
    );

    const onScrollEnd = () => {
        scrollY.addListener(({ value }) => {
            if (!refreshing && value < -100) {
                setTriggerRefresh(true); // 触发刷新
            }
        });
    };

    const computedTime = function (startT, endT) {
        // console.log('startT', startT);
        // if (!isValid(startT) || !isValid(endT)) return  "";
        const day1 = format(startT, "yyMMdd");
        const day2 = format(endT, "yyMMdd");
        if (day1 == day2) {
            return `${format(startT, "MM.dd")} ${format(startT, "mm:ss")}-${format(endT, "mm:ss")}`
        };
        return `${format(startT, "MM.dd")} ${format(startT, "mm:ss")}-${format(startT, "MM.dd")} ${format(endT, "mm:ss")}`
    };

    const memberAdmin = function (id) {
        router.push(`/activityDetail/activityAdmin/${id}`)
    };


    const ActivityItem = ({ item }) => {
        const { type } = item;
        return (
            <TouchableOpacity onPress={() => memberAdmin(item.activityId)}>
                <View style={styles.activityContainer}>
                    <View style={styles.activitybody}>
                        <View style={styles.activityBanner}>
                            <Image source={{ uri: item.coverUrl }} style={{ width: "100%", height: "100%" }} />
                            {
                                item.activityStatus == 1 && (
                                    <ImageBackground source={headerTagImg} style={styles.activityTagWarp}>
                                        <View style={[{ transform: [{rotateZ:'-45deg'}]}, styles.tag]}>
                                            <Text style={styles.tagText}>待开始</Text>
                                        </View>
                                    </ImageBackground>
                                )
                            }

                            {
                                (item.activityStatus == 2)  && (
                                    <ImageBackground source={headerTagImg} style={styles.activityTagWarp}>
                                        <View style={[{ transform: [{rotateZ:'-45deg'}]}, styles.tag]}>
                                            <Text style={styles.tagText}>进行中</Text>
                                        </View>
                                    </ImageBackground>
                                )
                            }



                            {
                                item.activityStatus == 3 && (
                                    <View style={styles.activityType}>
                                        <Text style={styles.activityTypeText}>已结束</Text>
                                    </View>
                                )
                            }

                            {
                                item.activityStatus === 4 && (
                                    <View style={styles.activityType}>
                                        <Text style={styles.activityTypeText}>已取消</Text>
                                    </View>
                                )
                            }

                        </View>
                        <View style={styles.activityContent}>
                            <View style={styles.activityTitleWarp}>
                                <Text
                                    style={styles.activityTitle}
                                    numberOfLines={2}
                                    ellipsizeMode="tail"
                                >{ item.title }</Text>
                            </View>
                            <View style={styles.activityTag}>
                                <Text style={styles.activityTagText}>{ item.typeName }</Text>
                            </View>
                            <View style={styles.activityDateWarp}>
                                <View style={styles.addressIcon}>
                                    <Image source={dateTimeIcon } style={{ width: '100%', height: "100%" }} />
                                </View>
                                <Text style={ styles.activityDate }>{ computedTime(item?.durationStartTime, item?.durationEndTime) }</Text>
                            </View>
                            <View style={styles.activityAdressWarp}>
                                <View style={styles.addressIcon}>
                                    <Image source={addressIcon} style={{ width: '100%', height: "100%" }} />
                                </View>
                                <Text style={styles.activityAdress}>{ item.destName }</Text>
                            </View>
                        </View>

                    </View>

                    {
                        item.activityStatus == 2 && (
                            <View style={styles.activityFooter}>
                                <View style={styles.joinList}>
                                    <View style={styles.joinListWarp}>
                                        {
                                            item.members.map((it:any, index: number) => {
                                                if (index == 0) {
                                                    return (
                                                        <View style={styles.joinAvator}>
                                                            <Image source={{ uri: it.avator }} style={{ width: "100%", height: "100%" }} />
                                                        </View>
                                                    )
                                                } else if (index <= 3 ) {
                                                    return (
                                                        <View style={[styles.joinAvator,styles.maLeft]}>
                                                            <Image source={{ uri:it.avator }} style={{ width: "100%", height: "100%" }} />
                                                        </View>
                                                    )
                                                }
                                            })
                                        }
                                        {
                                            item.activityStatus == 1 && (
                                                <View style={styles.joinContent}>
                                                    <Text style={styles.joinContentText}>正在招募...</Text>
                                                </View>
                                            )
                                        }

                                    </View>

                                </View>
                                <View style={styles.activityMoney}>
                                    <Text style={styles.activityMoneyText}>¥{ parseFloat(item?.ticketsPrice) }</Text>
                                </View>
                            </View>
                        )
                    }
                    {/*{*/}
                    {/*    activityType.waiting == type && (*/}
                    {/*        <View style={styles.activityFooter}>*/}
                    {/*           <TouchableOpacity onPress={() => setFoundTextModel(true)}>*/}
                    {/*               <View style={styles.activityMoney}>*/}
                    {/*                   <Text style={styles.activityMoneyText}>退出</Text>*/}
                    {/*               </View>*/}
                    {/*           </TouchableOpacity>*/}
                    {/*        </View>*/}
                    {/*    )*/}
                    {/*}*/}

                    {
                        (item.isComment === 0 && item.activityStatus == 3) && (
                            <View style={styles.activityFooterComment}>
                                <TouchableOpacity onPress={() => setFoundTextModel(true)}>
                                    <View style={styles.activityMoneyComment}>
                                        <Text style={styles.activityMoneyTextComment}>去评论</Text>
                                    </View>
                                </TouchableOpacity>
                            </View>
                        )
                    }

                </View>
            </TouchableOpacity>
        )
    };

    return (
        <>
            <FlatList
                data={data}
                renderItem={({ item }) => <ActivityItem item={item} />}
                keyExtractor={(item, index) => index.toString()}
                onEndReached={loadMoreData}
                onEndReachedThreshold={0.5} // 当滚动到距离底部还有50%的时候触发
                ListFooterComponent={renderFooter}
                refreshControl={
                    <RefreshControl
                        refreshing={refreshing}
                        // onRefresh={handleRefresh} // 绑定刷新函数
                        title={refreshing ? '' : refreshingText} // 在正在刷新状态时不显示文本
                        titleColor="#333" // 设置提示文字颜色
                        tintColor="transparent" // 隐藏刷新指示器
                    />
                }
                onScroll={handleScroll}
                onScrollEndDrag={onScrollEnd}
                ListHeaderComponent={<RefreshControlHeader refreshing={refreshing} text={refreshingText} />}
                ListEmptyComponent={<Empty title={"暂无活动"} />}
            />

            <Modal
                animationType="fade"
                transparent={true}
                visible={foundTextModel}
            >
                <TouchableOpacity
                    activeOpacity={1}
                    onPress={(event) => {
                        if (event.target === event.currentTarget) {
                            setFoundTextModel(false);
                        }
                    }}
                    style={styles.becameModelContainer}
                >
                    <View style={styles.becameModelWrap}>
                        <View style={styles.becameModelTitle}>
                            <Text style={styles.becameModelTitleText}>退出</Text>
                        </View>
                        <View>
                            <Text style={{textAlign: "center", marginBottom: 34, color: "#676978"}}>确定退出活动</Text>
                        </View>
                        <View style={styles.becameFootWrap}>
                            <TouchableOpacity onPress={() => setFoundTextModel(false)}>
                                <View style={styles.cancelBtn}>
                                    <Text style={styles.cancelBtnText} >取消</Text>
                                </View>
                            </TouchableOpacity>
                            <TouchableOpacity onPress={() => setFoundTextModel(false)}>
                                <View style={styles.okBtn}>
                                    <Text style={styles.okBtnText}>确认</Text>
                                </View>
                            </TouchableOpacity>
                        </View>
                    </View>
                </TouchableOpacity>

            </Modal>
        </>
    );
};

// 自定义的 TabBar 组件
const CustomTabBar = ({ navigationState, position, setIndex }) => {
    // 创建指示器的动态宽度和位置
    const inputRange = navigationState.routes.map((_, i) => i);
    const layoutWith = scaleSize(350);
    const translateX = position.interpolate({
        inputRange,
        outputRange: inputRange.map(i => i * layoutWith / 3 + ((layoutWith / 3) - layoutWith / 13) / 2),
        // outputRange: [48, 162], // 这里的值需要根据实际情况计算
    });


    return (
        <View style={styles.tabHeader}>
            <View style={styles.tabBar}>
                {navigationState.routes.map((route, i) => (
                    <TouchableOpacity
                        key={route.key}
                        onPress={() => setIndex(i)}
                        style={styles.tabItem}>
                        <Text style={{ color: navigationState.index === i ? '#EC6138' : 'black', textAlign: "left" }}>
                            {route.title}
                        </Text>
                    </TouchableOpacity>
                ))}
                {/* 自定义指示器 */}
                <Animated.View
                    style={[
                        styles.indicator,
                        { transform: [{ translateX }] },
                        { width: scaleSize(26) } // 指示器的宽度
                    ]}
                />
            </View>
        </View>
    );
};


export default function activityRouteScreen() {

    const router = useRouter();
    const layout = useWindowDimensions();


    const [index, setIndex] = React.useState(0);
    const [routes] = React.useState([
        { key: 'join', title: '我参加的' },
        { key: 'create', title: '我创建的' },
        { key: 'check', title: '活动审核' },
    ]);

    // const renderScene = SceneMap({
    //     join: JoinRoute,
    //     create: JoinRoute,
    //     check: JoinRoute
    // });

    const renderScene = ({ route }) => {
        switch (route.key) {
            case 'join':
                return <JoinRoute currentIndex={index} key={'join'}/>; // 传递当前索引给 FirstRoute
            case 'create':
                return <CreateRoute currentIndex={index} key={'create'} />;
            case 'check':
                return <CheckRoute currentIndex={index} key={'check'} />;
            default:
                return null;
        }
    };


    return (
        <View style={{ height: "100%", backgroundColor: "#F7F7F7" }}>
            <Stack.Screen
                options={{
                    title: '我的活动', // 设置屏幕标题
                    headerStyle: {
                        backgroundColor: '#fff', // 设置标题栏的背景颜色
                    },
                    headerShadowVisible: false, // 隐藏底部阴影和边框
                    headerBackTitleVisible: false,
                    headerTintColor: "#333",
                    headerLeft: () => (
                        <TouchableOpacity onPress={() => router.back()}>
                            <AntDesign name="left" size={19} color="#333" />
                            {/*<Ionicons name="arrow-back" size={30} color="#fff" style={{ paddingLeft: 15 }} />*/}
                        </TouchableOpacity>
                    ),
                }}
            />
            <TabView
                navigationState={{ index, routes }}
                renderScene={renderScene}
                onIndexChange={setIndex}
                initialLayout={{ width: layout.width }}
                renderTabBar={(props) => <CustomTabBar {...props} setIndex={setIndex} />} // 使用自定义的 TabBar
            />
        </View>

    );
}

const styles = StyleSheet.create({
    scene: {
        flex: 1,
        // justifyContent: 'center',
        // alignItems: 'center',
    },
    tabBar: {
        flexDirection: 'row',
        backgroundColor: 'white',
        position: 'relative', // 需要相对定位来放置指示器
        width:scaleSize(350),
        margin: "auto",
    },
    tabItem: {
        flex: 1,
        alignItems: 'center',
        paddingTop: 10,
        paddingBottom: 9,
        fontSize: 14,
        color: "#2A2B30",
    },
    indicator: {
        position: 'absolute',
        height: 3,
        backgroundColor: '#EC6138',
        bottom: 0,
        borderRadius: 5,
    },
    tabHeader: {
        backgroundColor: "#fff",
        borderBottomWidth: 1,
        borderBottomColor: "#F1F2F5",
        marginBottom: 12,
    },
    activityContainer: {
        // flexDirection: "row",
        marginLeft: 12,
        marginRight: 12,
        // height: scaleSize(164),
        backgroundColor: "#fff",
        borderRadius: 8,
        marginBottom: 12,
    },
    activitybody: {
        padding: 12,
        flexDirection: "row",

    },
    activityBanner: {
        position: "relative",
        width: scaleSize(110),
        height: scaleSize(110),
        backgroundColor: "blue",
        borderRadius: 4,
    },
    activityContent: {
        marginLeft: 10,
    },
    activityTitleWarp: {
        width: scaleSize(200),
    },
    activityTitle: {
        fontSize: 16,
        fontWeight: "bold",
        color: "#2A2B30",
        letterSpacing: 1.2,
        lineHeight: 22,
    },
    addressIcon: {
        width: scaleSize(11),
        height: scaleSize(11),
    },
    activityTag: {
        width: scaleSize(28),
        height: scaleSize(12),
        backgroundColor: "rgba(255,70,0,0.1)",
        borderRadius: 10,
        marginTop: 6,
    },
    activityTagText: {
        fontSize: 8,
        color: "#EC6138",
        textAlign: "center",
        lineHeight: 12,
    },
    activityDateWarp: {
        flexDirection: "row",
        alignItems: "center",
        marginTop: 6,
        marginBottom: 6,
    },
    activityDate: {
        marginLeft: 3,
        fontSize: 12,
        color: "#676978"
    },
    activityAdressWarp: {
        flexDirection: "row",
        alignItems: "center",
    },
    activityAdress: {
        fontSize: 12,
        color: "#676978",
        marginLeft: 3,
    },
    joinList: {
        flexDirection: "row",
        alignItems: "center",
        flex: 1,
    },
    activityFooter: {
        flexDirection: "row",
        paddingLeft: 12,
        paddingRight: 12,
        // justifyContent: "flex-start",
        alignItems: "center"
    },
    activityFooterComment: {
        flexDirection: "row",
        paddingLeft: 12,
        paddingRight: 12,
        justifyContent: "flex-end",
        alignItems: "center"
    },
    joinAvator: {
        width: scaleSize(20),
        height: scaleSize(20),
        backgroundColor: "red",
        borderRadius: 10,
        borderColor: "#fff",
        borderWidth: 1,
    },
    maLeft: {
        marginLeft: -7,
    },
    joinListWarp: {
        flexDirection: "row",
    },
    joinContent: {
        marginLeft: 10,
    },
    joinContentText: {
        color: "#333",
        fontSize: 12,
        fontWeight: "bold"
    },
    activityMoney: {
        width: 56,
        height: 24,
        backgroundColor: "#F7F8F9",
        borderRadius: 12,
        flexDirection: "row",
        justifyContent: "center",
        alignItems: "center",
        marginBottom: 12,
    },
    activityMoneyText: {
        color: "#FE7649",
        fontSize: 12,
    },
    activityMoneyComment: {
        width: 68,
        height: 26,
        // backgroundColor: "#F7F8F9",
        borderRadius: 12,
        flexDirection: "row",
        justifyContent: "center",
        alignItems: "center",
        marginBottom: 12,
        borderWidth: 1,
        borderColor: "#C0C3CE"
    },
    activityMoneyTextComment: {
        color: "#2A2B30",
        fontSize: 14,
    },
    activityTwoMoney: {
        width: 56,
        height: 24,
        backgroundColor: "#FE7649",
        borderRadius: 12,
        flexDirection: "row",
        justifyContent: "center",
        alignItems: "center",
        marginBottom: 12,
    },
    activityTwoMoneyText: {
        color: "#fff",
        fontSize: 12,
    },
    activityTagWarp: {
        position: "absolute",
        width: 38,
        height: 38,
        // backgroundColor: "red",
    },
    tag: {
        position: "absolute",
        top: 8,
        left: 0,
        zIndex: 10
    },
    tagText: {
        fontSize: 8,
        textAlign: "center",
        color: "#fff",
        marginTop: 1,
    },
    refreshHeader: {
        alignItems: 'center',
        padding: 20,
    },
    refreshIcon: {
        width: 12,
        height: 12,
        marginBottom: 10,
    },
    refreshText: {
        fontSize: 12,
        color: '#333',
    },
    activityType: {
        width: "100%",
        height: "100%",
        backgroundColor: "rgba(51,51,51,0.6)",
        position: "absolute"
    },
    activityTypeText: {
        color: "#fff",
        margin: "auto",
    },
    becameModelContainer: {
        backgroundColor: 'rgba(0,0,0, 0.7)',
        height: "100%",
    },
    becameModelWrap: {
        width: scaleSize(296),
        // height: scaleSize(270),
        backgroundColor: "#fff",
        margin: "auto",
        borderRadius: 8,
        paddingTop: 24,
        paddingLeft: 18,
        paddingRight: 18,
        paddingBottom: 20,
        position: "relative",
        zIndex: 9,
    },
    becameModelTitle: {
        marginBottom: 14,
    },
    becameModelTitleText: {
        textAlign: "center",
        fontSize: 16,
        // fontWeight: "bold"
        // color: "#2A2B30"
    },
    becameFootWrap: {
        // marginTop: 58,
        flexDirection: "row",
        justifyContent: "space-between",
        paddingLeft: 10,
        paddingRight: 10,
    },
    cancelBtn: {
        backgroundColor: "#F7F8F9",
        width: 114,
        height: 38,
        borderRadius: 19,
        flexDirection: "row",
        justifyContent: "center",
        alignItems: "center",
    },
    cancelBtnText: {
        // fontWeight: "bold",
    },
    okBtnText: {
        color: "#fff",
        fontWeight: "bold",
    },
    okBtn: {
        backgroundColor: "#EC6138",
        width: 114,
        height: 38,
        borderRadius: 19,
        flexDirection: "row",
        justifyContent: "center",
        alignItems: "center",
    },
});
